package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.example.myapplication.bean.User;
import com.example.myapplication.dao.MySQLiteOpenHelper;
import com.example.myapplication.databinding.ActivityMainRegisterBinding;
import com.example.myapplication.service.SharedPreferencesService;

public class MainActivityRegister extends AppCompatActivity {

    private ActivityMainRegisterBinding mainRegisterBinding;
    private Intent intent;
    private MySQLiteOpenHelper mySQLiteOpenHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_register);

        mainRegisterBinding = ActivityMainRegisterBinding.inflate(getLayoutInflater());
        setContentView(mainRegisterBinding.getRoot());

//注册
        mainRegisterBinding.registerBtn.setOnClickListener(view -> {
            String account = mainRegisterBinding.registerAccount.getText().toString().trim();
            String password = mainRegisterBinding.registerPassword.getText().toString().trim();
            String rePassword = mainRegisterBinding.registerConfirm.getText().toString().trim();
            mySQLiteOpenHelper = new MySQLiteOpenHelper(this);
            User user = mySQLiteOpenHelper.queryUserByAccount(account);
            if (user != null) {
                Toast.makeText(MainActivityRegister.this, "同名账号已存在", Toast.LENGTH_SHORT).show();
                return;
            }
            if (password.length() >= 6) {
                if (password.equals(rePassword)) {
                    // 通过验证新增用户
                    user = new User(null, account, password);
                    boolean isSuccess = mySQLiteOpenHelper.insertUser(user);
                    if (isSuccess) {
                        // 新增成功后，查询用户信息存储到 SharedPreferences 中
                        user = mySQLiteOpenHelper.queryUserByAccount(account);
                        SharedPreferencesService.saveUserInfo(MainActivityRegister.this, user.getUserId(), account, password);
                        Toast.makeText(MainActivityRegister.this, "注册成功", Toast.LENGTH_SHORT).show();
                        intent = new Intent(this, MainActivity2PageView.class);
                        startActivity(intent);
                    } else {
                        Toast.makeText(MainActivityRegister.this, "注册失败", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(MainActivityRegister.this, "密码不一致", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(MainActivityRegister.this, "密码长度不少于6位", Toast.LENGTH_SHORT).show();
            }
        });

// 已有账号
        mainRegisterBinding.registerHasAccount.setOnClickListener(view -> {
            intent = new Intent(this, MainActivityLogin.class);
            startActivity(intent);
            finish();

            /*返回栈操作（未测试）*/
//            // 移除返回栈顶部的Activity
//            FragmentManager fragmentManager = getSupportFragmentManager();
//            fragmentManager.popBackStack();
//            // 移除特定ID的Activity
//            int id = getResources().getIdentifier("my_activity", "id", getPackageName());
//            fragmentManager.popBackStack(id, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        });


    }

    /*————————————————————start——————————————————
     * 借鉴 https://blog.51cto.com/u_16175494/6870299 网址51CTO博客的代码
     * 未使用
     */
    /*private String generateCaptcha() {
        // 生成随机的验证码
        String captcha = generateRandomCaptcha();

        // 将验证码图片保存到本地
        saveCaptchaImage(captcha);

        return captcha;
    }

    private String generateRandomCaptcha() {
        // 随机生成4位验证码
        Random random = new Random();
        StringBuilder captcha = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            captcha.append(random.nextInt(10));
        }
        return captcha.toString();
    }

    private void saveCaptchaImage(String captcha) {
        // 创建一个Bitmap对象，并绘制验证码
        Bitmap bitmap = Bitmap.createBitmap(200, 100, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setTextSize(50);
        paint.setColor(Color.BLACK);
        canvas.drawText(captcha, 50, 50, paint);

        // 将Bitmap保存到本地
        File file = new File(Environment.getExternalStorageDirectory(), "captcha.png");
        try (FileOutputStream fos = new FileOutputStream(file)) {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/
    /*——————————————————end——————————————————*/
}